package com.yeraphael.filter;

import com.yeraphael.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;


@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        0.强转对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

//        1.获取请求
        StringBuffer requestURL = request.getRequestURL();
        String requestURI = request.getRequestURI();
        log.info("requestURL: " + requestURL);
        log.info("requestURI: " + requestURI);

//        2.判断请求url中是否包含login,如何包含 说明是登录操作，就放行
        if(requestURI.contains("login")){
            filterChain.doFilter(request, response);
            return;
        }

//        3.获取请求头中的令牌
        String token = request.getHeader("token");

//        4.判断令牌是否存在，如果不存在 响应401
        if(token == null){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }



//        5.验证令牌是否有效，如果解析失败，响应401
        try {
            Claims claims = JWTUtils.parseJWT(token);
            log.info("claims: " + claims);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.error("令牌解析错误："+e.getMessage());
            return;
        }

//        6.放行
        filterChain.doFilter(request, response);


    }

}
